#include "cpiaprocrwsetting.h"

CpiaProcSetting::CpiaProcSetting()
{
}

void CpiaProcSetting::updateSettings(){
    QFile file(cpia_file);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    rwsettings.clear();
    rosettings.clear();

    QTextStream in(&file);
    QString line = in.readLine();
    QRegExp settingrx("(\\w+):\\s+(\\w+)");

    bool rwsettings = false;
    while (!line.isNull()) {
        if(line.contains("read-write")) rwsettings = true;

        if(rwsettings && settingrx.indexIn(line) > -1)
        {
            this->rwsettings.insert(settingrx.cap(1), settingrx.cap(2));
        }
        else if(settingrx.indexIn(line)> -1)
        {
            this->rosettings.insert(settingrx.cap(1), settingrx.cap(2));
        }
        line = in.readLine();
    }

    file.close();
}

bool CpiaProcSetting::getBoolSetting(QString key)
{
    updateSettings();
    if(rwsettings.contains(key)) return rwsettings.value(key) == "1" || rwsettings.value(key) == "on" ? true: false;
    if(rosettings.contains(key)) return rosettings.value(key) == "1" || rosettings.value(key) == "on" ? true: false;

}

int CpiaProcSetting::getIntSetting(QString key)
{
    updateSettings();
    if(rwsettings.contains(key)) return rwsettings.value(key).toInt();
    if(rosettings.contains(key)) return rosettings.value(key).toInt();

    return -1;
}

QString CpiaProcSetting::getStringSetting(QString key)
{
    updateSettings();
    if(rwsettings.contains(key)) return rwsettings.value(key);
    if(rosettings.contains(key)) return rosettings.value(key);

}

void CpiaProcSetting:: setIntSetting(QString key, int value)
{

    if(!rwsettings.contains(key)) return;
    QFile file(cpia_file);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream to(&file);

    to << key << ": " << value << endl;


    file.close();
    updateSettings();
}

void CpiaProcSetting::setBoolOnOffSetting(QString key, bool value)
{
    if(!rwsettings.contains(key)) return;
    QFile file(cpia_file);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream to(&file);

    to << key << ": " << (value ? "on":"off") << endl;


    file.close();
    updateSettings();
}

void CpiaProcSetting::setBoolSetting(QString key, bool value)
{
    if(!rwsettings.contains(key)) return;
    QFile file(cpia_file);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream to(&file);

    to << key << ": " << (value ? "1":"0") << endl;


    file.close();
    updateSettings();
}

void CpiaProcSetting::setStringSetting(QString key, QString value)
{
    if(!rwsettings.contains(key)) return;
    QFile file(cpia_file);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream to(&file);

    to << key << ": " << value << endl;


    file.close();
    updateSettings();
}
